// utils/mqtt.js
import mqtt from 'mqtt/dist/mqtt'

class MQTTClient {
  constructor() {
    this.client = null
    this.subscriptions = new Map()
    this.reconnectTimer = null
    this.config = {
      host: 'mqtt://your-broker.com',
      options: {
        clientId: 'uni-app-' + Date.now(),
        keepalive: 60,
        clean: true,
        reconnectPeriod: 5000
      }
    }
  }

  init() {
    if (!this.client) {
      this.connect()
    }
  }

  connect() {
    this.client = mqtt.connect(this.config.host, this.config.options)

    this.client.on('connect', () => {
      console.log('MQTT Connected')
      this.resubscribe()
    })

    this.client.on('message', (topic, message) => {
      this.handleMessage(topic, message)
    })

    this.client.on('error', (err) => {
      console.error('MQTT Error:', err)
    })

    this.client.on('close', () => {
      console.log('MQTT Connection closed')
      this.scheduleReconnect()
    })
  }

  subscribe(topic, callback) {
    if (!this.subscriptions.has(topic)) {
      this.subscriptions.set(topic, new Set())
      if (this.client?.connected) {
        this.client.subscribe(topic)
      }
    }
    this.subscriptions.get(topic).add(callback)
  }

  unsubscribe(topic, callback) {
    if (this.subscriptions.has(topic)) {
      const callbacks = this.subscriptions.get(topic)
      callbacks.delete(callback)
      if (callbacks.size === 0) {
        this.subscriptions.delete(topic)
        if (this.client?.connected) {
          this.client.unsubscribe(topic)
        }
      }
    }
  }

  handleMessage(topic, message) {
    if (this.subscriptions.has(topic)) {
      const callbacks = this.subscriptions.get(topic)
      callbacks.forEach(cb => cb(message.toString()))
    }
  }

  resubscribe() {
    if (this.client?.connected) {
      const topics = Array.from(this.subscriptions.keys())
      if (topics.length > 0) {
        this.client.subscribe(topics)
      }
    }
  }

  scheduleReconnect() {
    if (!this.reconnectTimer) {
      this.reconnectTimer = setTimeout(() => {
        this.reconnectTimer = null
        this.connect()
      }, 5000)
    }
  }

  destroy() {
    if (this.client) {
      this.client.end()
      this.client = null
    }
    this.subscriptions.clear()
    clearTimeout(this.reconnectTimer)
  }
}

export const mqttClient = new MQTTClient()
